<template>
  <div class="play-control-box">
    <div class="play-control-left">
      <img class="song-cover" @click="showDrawer" :src="songCover==''?'https://app.feparks.com/app/v3/bench/images/notfound.png':songCover" alt="" srcset="">
      <div class="song-info">
        <div class="song-top">
          <p class="song-name">{{ songName}} | {{ songAlia }}<p class="song-love"><i class="iconfont icon-xihuan"></i></p></p>
        </div>
        <p class="song-author">{{ songAuthor }}</p>
      </div>
    </div>
    <div class="play-control-center">
      <ul class="play-control-btns">
        <li class="play-control-btn pre" @click="prevSong">
          <i class="iconfont icon-shangyiqu"></i>
        </li>
        <li class="play-control-btn play" @click="playControl">
          <i :class="isPlaying==true?'iconfont icon-zanting':'iconfont icon-shipinbofangshibofang'"></i>
        </li>
        <li class="play-control-btn next" @click="nextSong">
          <i class="iconfont icon-xiayiqu"></i>
        </li>
      </ul>
      <!-- 进度条 -->
      <div class="steep">
        <p class="current-time">{{ currentTime }}</p>
        <div class="play-steep-outlin" ref="playSteepOut">
          <div class="play-steep-in" ref="playSteepIn">
          </div>
        </div>
        <p class="duraption">{{ songTime }}</p>
      </div>
    </div>
    <div class="play-control-right">
      <ul class="play-control-right-btns">
        <li class="play-control-right-btn">
          <i class="iconfont icon-yinliang"></i>
        </li>
        <li class="play-control-right-btn">
          <i class="iconfont icon-24gf-playlistMusic" @click.prevent.stop="playListVisable"></i>
        </li>
      </ul>
    </div>
    <!-- music source -->
    <audio id="qingting" :src="songUrl"></audio>
    <el-drawer
      size="100%"
      custom-class="songDrawer"
      title="我是标题"
      :visible.sync="drawer"
      direction="btt"
      :modal="false"
      :with-header="false">
      <song-drawer :drawerSongInfo="drawerSongInfo" :drawerSongWord="drawerSongWord">
        <template #top>
          <tabar>
            <template #left>
              <span class="iconfont icon-shanglajiantou close-song-drawer" @click="drawer=false"></span>
            </template>
            <template #right>
              <p></p>
            </template>
          </tabar>
        </template>
      </song-drawer>
    </el-drawer>
    <!-- 播放列表 -->
    <div class="play-list-box" ref="playList" v-show="showPlayList">
      <div class="play-list-top">
        <h3 class="play-list-title">播放列表</h3>
        <div class="play-tips">
          <span class="play-count">总{{ musicList.length }}首</span>
          <div class="play-btns">
            <p class="play-btn">收藏全部</p>
            <p class="play-btn" @click="clearList">清空列表</p>
          </div>
        </div>
      </div>
      <div class="play-container">
        <ul class="play-content">
          <li :class="songId==item.id?'music-item music-item-active':'music-item'" v-for="(item,index) in musicList" :key="item.id+index">
            <span class="music-name" @click="playCurrentMusic(item.id)">{{item.name}}</span>
            <span class="music-author">{{item.author}}</span>
            <i class="music-copy iconfont icon-lianjie" @click="copy(item.url)"></i>
            <span class="music-duration">{{ item.time | formatPlayTime}}</span>
          </li>
        </ul>
      </div>
    </div>
    <div class="cat-steep">
      <img class="cat-img" :src="catSteep" alt="" srcset="">
    </div>
  </div>
</template>

<script>
import {formatPlayTime} from '@/util/filters'
import {mapState,mapActions,mapMutations} from 'vuex'
import SongDrawer from '@/components/SongDrawer/SongDrawer'
import Tabar from '@/components/Tabar/Tabar'
import {getMusicCover,getMusicSongWord} from '@/request/Api.js'
export default {
  name:'PlayControl',
  mounted(){
    this.formatOn()
    this.steepClick()
    // 全局添加点击空白关闭事件
    document.addEventListener('click',(e)=>{
      if(this.$refs.playList){
        let _self = this.$refs.playList.contains(e.target)
        if(!_self){
          this.showPlayList = false
        }
      }
    })
  },
  components:{SongDrawer,Tabar},
  props:{
    songCover:{
      default:'',
      type:String
    },
    songUrl:{
      default:'',
      type:String
    },
    songName:{
      default:'未命名歌曲',
      type:String
    },
    songId:{
      default:'',
      type:[Number,String]
    },
    songAlia:{
      default:'',
      type:String
    },
    songAuthor:{
      default:'未知作者',
      type:String
    },
    musicList:{
      default:()=>[],
      type:Array
    }
  },
  data(){
    return {
      isPlaying:false,
      drawer: false,
      currentTime:'00:00',
      songTime:'00:00',
      catSteep:require('../../assets/images/stop-steep.gif'),
      showPlayList:false,
      drawerSongInfo:{},
      drawerSongWord:[]
    }
  },
  methods:{
     ...mapActions('Music',['getMusicCover','getMusicUrl']),
    //  点击音乐封面处理函数
    showDrawer(){
      this.drawer = !this.drawer
      if(this.drawer){
        this.getMusicInfo()
        this.getMusicSongWord()
        this.$bus.$emit('getComment',this.songId)
      }
    },
    //  获取音乐详情传递给drawer
    async getMusicInfo(){
      const {data:res} = await getMusicCover(this.songId)
      if(res.code!==200){
        return
      }
      this.drawerSongInfo = res
      console.log('当前音乐的数据信息',res);
    },
    // 获取音乐歌词
    async getMusicSongWord(){
      const {data:res} = await getMusicSongWord(this.songId)
      if(res.code!==200){
        return
      }
      this.drawerSongWord = this.formatMusicLrc(res.lrc.lyric)
    },
    playControl(){
      let audio =document.querySelector('#qingting');
      // 播放逻辑
      if(!this.isPlaying){
        this.catSteep = require('../../assets/images/steep.gif')
        audio.play()
        let timp = audio.duration * 1000
        this.songTime = formatPlayTime(timp)
        this.musicSteep(audio)
      }else {
        // 暂停
        audio.pause()
        this.catSteep = require('../../assets/images/stop-steep.gif')
      }
      this.isPlaying = !this.isPlaying
    },
    // 上一曲
    prevSong(){
      let index = this.musicList.findIndex(item=>{
        console.log(item.id,this.songId);
        return item.id==this.songId
      })
      if(index==0){
        let idx = this.musicList.length - 1
        this.newSong(this.musicList[idx].id)
      }else {
        this.newSong(this.musicList[index-1].id)
      }
    },
    nextSong(){
      let index = this.musicList.findIndex(item=>{
        console.log(item.id,this.songId);
        return item.id==this.songId
      })
      if(index==this.musicList.length - 1){
        this.newSong(this.musicList[0].id)
      }else {
        this.newSong(this.musicList[index + 1].id)
      }
    },
    // 监控音乐播放进度函数
    musicSteep(audio){
      audio.oncanplay = () => {
        let timp = audio.duration * 1000
        this.songTime = formatPlayTime(timp)
      }
      audio.addEventListener('timeupdate',()=>{
        let playSteepInDom = document.querySelector('.play-steep-in')
        let duration = audio.duration
        let currentTime = audio.currentTime
        this.currentTime = formatPlayTime(audio.currentTime * 1000)
        // 进度条百分比
        let sp =  (currentTime / duration * 100).toFixed(2)
        // debugger
        playSteepInDom.style.width = sp + '%' 
        // 播放到尽头
        if(sp >= 100){
          this.isPlaying = false
          audio.currentTime = 0
          this.$refs.playSteepIn.style.width = 0 + '%' 
          this.nextSong()
        }
      })
    },
    // 进度条拖拽事件
    steepClick(){
      let steepDom = this.$refs.playSteepOut
      var audio =document.querySelector('#qingting');
      steepDom.addEventListener('click',e => {
        let clientX = e.clientX
        let _x = clientX - steepDom.offsetLeft 
        let sp = _x / steepDom.clientWidth * 100
        let duration = audio.duration
        audio.currentTime = sp / 100 * duration
        this.$refs.playSteepIn.style.width = sp + '%' 
        // 判断如果不是播放状态就要直接播放
        if(!this.isPlaying){
          this.playControl()
        }
      },false)
    },
    // 暴露 格式化当前播放进度
    formatSteep(){
        this.isPlaying = false
        this.playControl()
    },
    formatOn(){
      this.$bus.$on('formatSteep',()=>{
        this.formatSteep()
      })
    },
    // 播放列表显示控件
    playListVisable(){
      this.showPlayList = !this.showPlayList
    },
    clearList(){
      this.$bus.$emit('clearList')
    },
    newSong(id){
      this.getMusicCover(id),
      this.getMusicUrl(id)
      Promise.all([this.getMusicCover(id),this.getMusicUrl(id)]).then(val=>{
        this.formatSteep()
      }).catch(err=>{
        console.log('失败');
      })
    },
    // 点击音乐列表的处理函数
    playCurrentMusic(id){
      this.newSong(id)
    },
    copy(url){
      navigator.clipboard.writeText(url).then(res=>{
         this.$notify({
            title: '复制音乐链接成功',
            message: '音乐路径复制成功',
            type: 'success',
            duration:1500
          });
      })
    },
    /**
     * 1.需要转化为的格式为[{time:'',lrc:''},{time:'',lrc:''}]
     * 2.思路
     * 3.根据\n转化为数组
     * 4.
     * */ 
    formatMusicLrc(songWord){
      let arr = songWord.split('\n')
      let newArr = new Array()
        for (let i=0;i<arr.length;i++){
            let obj = {}
            let min = arr[i].slice(arr[i].indexOf('[')+1,arr[i].indexOf(':'))
            let sec = arr[i].slice(arr[i].indexOf(':')+1,arr[i].indexOf(']'))
            let time = min*60 + Math.floor(sec)
            obj['time'] = time
            obj['lrc'] = arr[i].slice(arr[i].indexOf(']')+1)
            newArr.push(obj)
        }
      return newArr
    },
  }
}
</script>

<style lang="less" scoped>
#qingting {
  width: 100%;
  display: none;
}
.play-control-box {
  z-index: 999;
  display: flex;
  align-items: center;
  position: fixed;
  padding: .4rem .6rem;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 4rem;
  background: #fff;
  box-shadow: 0px 0px 3px #ccc;
  .play-control-left,.play-control-right {
    display: flex;
    align-items: center;
    font-size: .7rem;
    width: 20%;
    height: 100%;
    background: rgba(247, 247, 247, 0);
  }
  .song-cover {
    cursor: pointer;
    width: 2.8rem;
    height: 2.8rem;
    object-fit: cover;
    border-radius: 5px;
  }
  .play-control-center {
    width: 60%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    .play-control-btns {
      display: flex;
      align-items: center;
      .play-control-btn {
        cursor: pointer;
        transition: .3s;
        margin:0px 2rem;
      }
    }
    .play {
      width: 2rem;
      height: 2rem;
      text-align: center;
      line-height: 2rem;
      border-radius: 100%;
      background: rgb(245, 245, 245);
      &:hover {
        background: rgb(229, 229, 229);
      }
    }
    .steep {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      .current-time,.duraption {
        color: rgb(159, 159, 159);
        font-size: .5rem;
        display: inline-block;
      }
      .play-steep-outlin {
        display: inline-block;
        margin: .4rem 1rem;
        cursor: pointer;
        position: relative;
        width: 50%;
        border-radius: 2px;
        height: .2rem;
        background: rgb(206, 206, 206);
      }
      .play-steep-in {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 0%;
        height: 100%;
        border-radius: 2px;
        background: rgb(255, 78, 78);
      }
    }
  }
  .play-control-right {
    .play-control-right-btns {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      .play-control-right-btn {
        margin: 0px .4rem;
        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }
  }
  .song-info {
    height: 100%;
    padding-left: .4rem;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    .song-top {
      display: flex;
      width: 100%;
      align-items: center;
      .song-name {
        width: 80%;
        max-width: 80%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .song-love {
        width: 20%;
      }
    }
  }
}
// 上拉
::v-deep.el-drawer__wrapper {
  height: calc(100% - 4rem);
  box-shadow: 0px -1px 3px #9f7d7d;
}
::v-depp.el-drawer__open {
  height: 100%;
}
::v-deep.el-drawer__open .el-drawer.btt  {
  z-index: 89;
  height: 100% !important;
  box-shadow: none;
}
.play-list-box {
  z-index: 99;
  overflow: hidden;
  position: fixed;
  right: 0px;
  top: 50px;
  width: 23rem;
  height: calc(100vh - 50px - 4rem);
  background: #fff;
  box-shadow: -1px 0px 1px #eee,
              0px 1px 1px #eee;
  .play-list-top {
    height: 4rem;
    padding: .6rem;
    box-shadow: 0px 1px 1px #eee,
                0px -1px 1px #eee;
    .play-tips {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .play-count {
        font-size: .6rem;
        color: rgb(204, 204, 204);
      }
      .play-btns {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .play-btn {
          cursor: pointer;
          font-size: .84rem;
          margin: .4rem;
          &:nth-child(1){
            color: rgb(22, 22, 22);
          }
          &:nth-child(2){
            color: rgb(103, 148, 197);
          }
        }
        .play-btn:nth-child(2):hover {
             color: rgb(24, 83, 147);
          }
      }
    }
  }
  // 歌单内容
  .play-container {
    overflow-y: scroll;
    height: calc(100% - 4rem);
    width: 100%;
    .play-content {
      width: 100%;
      .music-item {
        transition: .3s;
        width: 100%;
         padding: .4rem .6rem;
        &:nth-child(even){
          background: #fafafa;
        }
        .music-name {
          cursor: pointer;
          font-size: .7rem;
          color: #000;
          display: inline-block;
          width: 50%;
          max-width: 50%;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
        .music-author {
          font-size: .7rem;
          display: inline-block;
          width: 25%;
          color: rgb(54, 53, 53);
          max-width: 25%;
        }
        .music-copy {
          cursor: pointer;
          font-size: .7rem;
          margin-right: .4rem;
        }
        .music-duration {
          font-size: .7rem;
          margin-left: .4rem;
          color: rgb(204, 204, 204);
        }
      }
      .music-item:hover {
        background: rgb(245,245,245);
      }
      .music-item-active .music-name{
        color: red;
      }
    }
  }
}


// 点击歌曲进入详情
.close-song-drawer {
  padding-left: .4rem;
  cursor: pointer;
}
.cat-steep {
  display: flex;
  justify-content: center;
  align-items: center;
}
.cat-img {
  width: 80%;
}
</style>